<template>
  <div class="product-list">
    <div class="container">
      <!-- 搜索和筛选区域 -->
      <div class="search-filter">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品..."
              clearable
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="selectedCategory"
              placeholder="选择分类"
              clearable
              @change="handleCategoryChange"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="resetFilters">重置筛选</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 商品列表 -->
      <div class="products-grid" v-loading="loading">
        <el-row :gutter="20">
          <el-col
            v-for="product in products"
            :key="product.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="4"
          >
            <el-card class="product-card" shadow="hover">
              <div class="product-image">
                <img
                  :src="product.imageError ? '/placeholder.jpg' : (product.image || '/placeholder.jpg')"
                  :alt="product.name"
                  @error="handleImageError(product)"
                />
              </div>
              <div class="product-info">
                <h3 class="product-name" @click="goToDetail(product.id)">
                  {{ product.name }}
                </h3>
                <p class="product-description">{{ product.description }}</p>
                <div class="product-price">
                  <span class="price">¥{{ product.price }}</span>
                  <span class="stock">库存: {{ product.stock }}</span>
                </div>
                <div class="product-actions">
                  <el-button
                    type="primary"
                    size="small"
                    @click="addToCart(product)"
                    :disabled="product.stock <= 0"
                  >
                    加入购物车
                  </el-button>
                  <el-button
                    type="default"
                    size="small"
                    @click="goToDetail(product.id)"
                  >
                    查看详情
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="seckill(product)"
                    :disabled="product.stock <= 0"
                  >
                    立即秒杀
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && products.length === 0"
          description="暂无商品"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="products.length > 0">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @update:current-page="handleCurrentChange"
          @update:page-size="handleSizeChange"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getProductList, getProductsByCategory, searchProducts } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'
import { seckillOrder } from '@/api/seckill'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 响应式数据
const products = ref([])
const categories = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 方法
const fetchProducts = async () => {
  try {
    loading.value = true
    let response
    
    if (searchKeyword.value) {
      response = await searchProducts(searchKeyword.value)
    } else if (selectedCategory.value) {
      response = await getProductsByCategory(selectedCategory.value)
    } else {
      response = await getProductList()
    }
    
    if (response.data) {
      // 为每个商品加 imageError 字段
      products.value = response.data.map(item => ({ ...item, imageError: false }))
      total.value = response.data.length
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const response = await getCategoryList()
    if (response.data) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

const handleCategoryChange = () => {
  currentPage.value = 1
  fetchProducts()
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  currentPage.value = 1
  fetchProducts()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const goToDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const addToCart = async (product) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const success = await cartStore.addItemToCart(product.id, 1)
    if (success) {
      ElMessage.success('已添加到购物车')
    }
  } catch (error) {
    console.error('添加购物车失败:', error)
  }
}

const seckill = async (product) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  try {
    const response = await seckillOrder(product.id)
    if (response.code === 200) {
      ElMessage.success('秒杀成功！正在跳转到秒杀订单列表')
      // 跳转到个人中心并激活“秒杀订单”Tab
      router.push({ path: '/user', query: { tab: 'seckill' } })
    } else {
      ElMessage.error(response.message || '秒杀失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '秒杀失败')
  }
}

const handleImageError = (product) => {
  product.imageError = true
}

// 生命周期
onMounted(() => {
  fetchProducts()
  fetchCategories()
})
</script>

<style scoped>
.product-list {
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-filter {
  margin-bottom: 30px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.products-grid {
  margin-bottom: 30px;
}

.product-card {
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 15px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  text-align: center;
}

.product-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-name:hover {
  color: #409eff;
}

.product-description {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.stock {
  font-size: 12px;
  color: #999;
}

.product-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.pagination {
  text-align: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .search-filter .el-row {
    margin-bottom: 15px;
  }
  
  .search-filter .el-col {
    margin-bottom: 10px;
  }
  
  .product-actions {
    flex-direction: column;
  }
}
</style> 